package com.damon.utils;

import java.net.Socket;

import com.damon.Entity.WcsDvcEntity;
import com.damon.log.WcsLog;

public class SocketUtil {
	
	/**
	 * ps:连接socket，同时添加其他操作
	 * 1、socketIsLive标记
	 * 2、向状态栏中添加该设备
	 */
	public static void connectSocket(WcsDvcEntity wcsDvcEntity,Boolean socketIsLive,Socket socket) {
		WcsLog logger = LogUtil.getLogger(SocketUtil.class,wcsDvcEntity);
		try {
			if (!socket.isClosed()) {
				socket.close();
			}
			socket = new Socket(wcsDvcEntity.getDvcIp(), Integer.valueOf(wcsDvcEntity.getPort()));
			socketIsLive = true;
			synchronized (GlobalOjbectUtil.getDvcList()) {
				GlobalOjbectUtil.addDvcNo(wcsDvcEntity.getDvcNo());
			}
		} catch (Exception e) {
			logger.error("创建socket失败,异常信息："+e.getMessage(),e);
			e.printStackTrace();
		}
	}
	
	/**
	 * ps:关闭socket，同时执行其他操作
	 * 1、更改socketIsLive标记
	 * 2、从状态栏中移除该设备
	 */
	public static void closeSocket(WcsDvcEntity wcsDvcEntity,Boolean socketIsLive,Socket socket) {
		WcsLog logger = LogUtil.getLogger(SocketUtil.class,wcsDvcEntity);
		try {
			socketIsLive = false;
			if (!socket.isClosed()) {
				socket.close();
			}
			synchronized (GlobalOjbectUtil.getDvcList()) {
				GlobalOjbectUtil.removeDvcNo(wcsDvcEntity.getDvcNo());
			}
		} catch (Exception e) {
			logger.error("关闭socket失败,异常信息："+e.getMessage(),e);
			e.printStackTrace();
		}
	}
}
